
<template>
  <!-- <div>本地商品库</div> -->
  <div class="shop">
    <div class="top">
      <el-button size="small" type="primary" @click="exportWoodsStore">导出数据</el-button>
      <el-button size="small" type="primary" @click="openPageDialog">选中商品加入当前专场</el-button>
      <el-button size="small" type="primary" @click="openCouponDialog">选中商品加入优惠券</el-button>
      <el-button class="search" size="small" type="primary" @click="searchSupplyChain">搜索</el-button>
      <el-input
        class="search input"
        size="small"
        v-model="product_no"
        placeholder="输入商品编号查询"
        clearable
      ></el-input>
      <el-input class="search input" size="small" v-model="title" placeholder="输入商品名称查询" clearable></el-input>

      <el-select
        style="width:130px;"
        size="small"
        v-model="on_sale"
        filterable
        class="search"
        placeholder="商品状态"
      >
        <el-option label="全部" :value="0">全部</el-option>
        <el-option label="售卖中" :value="5"></el-option>
        <el-option label="未上架" :value="15"></el-option>
      </el-select>

      <el-select
        style="width:180px;"
        size="small"
        v-model="cate_id"
        filterable
        class="search"
        placeholder="请选择分类"
      >
        <el-option
          v-for="item in categoryList"
          :key="item.id"
          :label="item.cate_name"
          :value="item.id"
        ></el-option>
      </el-select>
      <el-select
        style="width:130px;"
        size="small"
        v-model="product_type"
        filterable
        class="search"
        placeholder="商品类型"
      >
        <el-option label="全部" :value="0">全部</el-option>
        <el-option label="纯红包商品" :value="1"></el-option>
        <el-option label="补贴商品" :value="2"></el-option>
        <el-option label="异动商品" :value="3"></el-option>
      </el-select>
      <el-select
        style="width:180px;"
        size="small"
        v-model="page_id"
        filterable
        class="search"
        placeholder="优选推荐"
      >
        <el-option v-for="item in pageList" :key="item.id" :label="item.title" :value="item.id"></el-option>
      </el-select>
      <el-select
        style="width:180px;"
        size="small"
        v-model="label_id"
        filterable
        class="search"
        placeholder="标签筛选"
      >
        <el-option v-for="item in labelList" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
    </div>
    <el-table
      :data="tableData"
      style="width:100%"
      max-height="680"
      :cell-style="tc"
      :header-cell-style="tccolor"
      @selection-change="handleSelectionChange"
                        @sort-change="tblSort"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="商品编号" prop="product_no" width="120"></el-table-column>
      <el-table-column label="商品id" prop="id"></el-table-column>
      <el-table-column label="商品名称" prop="title" width="210"></el-table-column>
      <el-table-column label="商品图片" width="180">
        <template slot-scope="scope">
          <div class="img">
            <img
              :key="scope.row.ID"
              style="width:100px;"
              :src="scope.row.img_url ? scope.row.img_url : errorImg"
              alt
            />
          </div>
          <p class="more" @click="lookMoreShop(scope.row.product_no)">（更多）</p>
        </template>
      </el-table-column>
      <el-table-column label="商品分类" prop="cate_name" width="140"></el-table-column>
      <el-table-column label="供货成本价"
                        @sort-change="tblSort" sortable="custom" prop="supply_min_price">
        <template slot-scope="scope">
          <p>¥ {{scope.row.supply_min_price}}</p>
        </template>
      </el-table-column>
      <el-table-column label="运费成本">
        <template slot-scope="scope">
          <p>¥ {{scope.row.supply_freight_price}}</p>
        </template>
      </el-table-column>
      <el-table-column label="销售价">
        <template slot-scope="scope">
          <p>¥ {{scope.row.price}}</p>
        </template>
      </el-table-column>
      <el-table-column label="红包抵扣">
        <template slot-scope="scope">
          <p>¥ {{scope.row.red_packet_discount_price}}</p>
        </template>
      </el-table-column>
      <el-table-column label="商品库存" prop="stock"></el-table-column>
      <el-table-column label="展示排序" width="100px"
                        @sort-change="tblSort" sortable="custom" prop="order_sort">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.order_sort"
            type="number"
            @blur="orderSortChange(scope.row.product_no, scope.row.order_sort)"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品SKU">
        <template slot-scope="scope">
          <p class="more" @click="watchSkuDetail(scope.row.product_no)">查看</p>
        </template>
      </el-table-column>
      <el-table-column label="商品标签" width="200px">
        <template slot-scope="scope">
          <div @click="showLabelDialog(scope.row.id)">
            <span
              v-for="(item, index) in scope.row.product_label"
              :key="index"
              :style="{ color: item.color, border: `1px solid ${item.color}`}"
              class="label"
            >{{ item.name }}</span>
            <p v-if="scope.row.product_label.length === 0" class="setting-label">设置标签</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="推荐">
        <template slot-scope="scope">
          <i
            @click="recommendShopStore(scope.row.id,scope.row.on_sale)"
            class="el-icon-circle-check rec_success"
            v-if="scope.row.is_recommend == 1"
          ></i>
          <i
            @click="recommendShopStore(scope.row.id,scope.row.on_sale)"
            class="el-icon-circle-close rec_failure"
            v-else
          ></i>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="on_sale_word">
        <!-- <template slot-scope="scope">
          <p v-if='scope.row.status==1'>未上架</p>
          <p v-if='scope.row.status==0'>上架中</p>
        </template>-->
      </el-table-column>
      <el-table-column label="选品操作" fixed="right" width="320">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="selectShopToStore(scope.row.product_no)">编辑</el-button>
          <el-button
            v-if="scope.row.on_sale == 15"
            size="mini"
            type="primary"
            @click="updateStoreShop(scope.row.product_no)"
          >上架</el-button>
          <el-button
            v-if="scope.row.on_sale == 5"
            size="mini"
            type="danager"
            @click="updateDownStoreShop(scope.row.product_no)"
          >下架</el-button>
          <el-button size="mini" @click="gotoSaleDaily(scope.row.id)">销售日志</el-button>
          <el-button size="mini" @click="deleteWoods(scope.row.product_no)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-col :span="24">
      <div class="pagination">
        <el-pagination
          background
          @current-change="pageChange"
          :current-page="page"
          :page-size="size"
          layout="total, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-col>

    <!--商品SKU信息-->
    <jdialog title="商品SKU信息" :visible.sync="isShowSKUInformtion" width="800px">
      <skudetail
        :visible="isShowSKUInformtion"
        :currentId="skuId"
        @close="isShowSKUInformtion = false"
        @showSkuInfoDetail="certainshowSKUInfordetail"
      ></skudetail>
    </jdialog>

    <!--同步商品库-->
    <!-- <jdialog title="商品数据同步" :visible.sync="isShowSynchronism" width="500px">
      <div class="syncdata">
         <div class='sync-load' v-loading="loading"></div>
         <div class="sync-ing">正在同步中，请勿关闭</div>
        <div class="sync_num">已更新商品总数：{{syncShopNum}}件</div>
      </div>
    </jdialog>-->

    <!--商品图片  :n="img_arr.length"-->
    <jdialog title="商品图片查看" :visible.sync="isShowShopImg" width="640px">
      <div class="sku_pic">
        <div v-for="(item,index) in img_arr" :key="index" class="main_sku">
          <img
            style="width:160px;height:160px;"
            class="sku_pic_margin"
            :src="item? item : errorImg"
            alt
          />
          <p v-if="index ==0" class="main_img">商品主图</p>
          <p v-else class="other_img main_img">商品轮播图</p>
        </div>
      </div>
    </jdialog>
    <!-- 选中商品加入专场（可多选） -->
    <el-dialog title="选中商品加入专场（可多选）" :visible.sync="dialogVisible" width="30%">
      <el-checkbox-group v-model="checkList">
        <el-checkbox v-for="item in pageList" :key="item.id" :label="item.id">{{item.title}}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addToSpecialSession">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 选中商品加入优惠券（可多选） -->
    <el-dialog title="选中商品加入优惠券（可多选）" :visible.sync="dialogCouponVisible" width="50%">
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          v-for="item in couponList"
          :key="item.id"
          :label="item.id"
          style="margin-bottom:10px"
        >
          <span>{{item.price}}</span>
          <span style="margin:0 15px">发券期：{{item.use_start_time}} / {{item.use_end_time}}</span>
          <span>有效期：{{item.publish_start_time}} / {{item.publish_end_time}}</span>
        </el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addToCouponShop">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="选择标签，最多选2个" :visible.sync="labelDialogVisible" width="30%">
      <el-checkbox-group v-model="labelCheckList">
        <el-checkbox v-for="item in labelList" :key="item.id" :label="item.id">{{item.name}}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="labelCancel">取 消</el-button>
        <el-button type="primary" @click="updateProductLabel">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import errorImg from "@/assets/images/error_img.png";
import skudetail from "./skudetailInfor";
import {
  selfProductSearchList,
  supplyProductImgList,
  selfProductOnsaleUpdate,
  simpleGoodsTypeList,
  selfProductRemove,
  supplyRecommendProduct,
  addToProductPage,
  getPageList,
  easyCouponList,
  isShopCouponChange,
  getLabelList,
  setOrderSort,
  updateLabel
} from "@/api/autarky";
import { API_BASE_URL } from "@/config";
// import uploadImg from "@/components/uploadImg";
export default {
  components: {
    // uploadImg
    skudetail
  },
  data() {
    return {
      title: "",
      product_no: "",
      cate_id: "",
      on_sale: "",
      product_type: undefined,
      is_export: 0,
      tableData: [],
      errorImg,
      page: 1,
      size: 20,
      total: 0,

      //商品SKU信息
      isShowSKUInformtion: false,
      skuId: "",
      checkList: [],

      //商品图片查看
      isShowShopImg: false,
      img_arr: [],

      categoryList: [],
      selectedItems: [], // 选中的数据
      pageList: [], // 专场列表
      couponList:[],
      page_id: "", // 选中专场id
      labelList: [], //标签列表
      label_id: [], // 选中标签id
      dialogVisible: false,
      dialogCouponVisible: false,
      labelDialogVisible: false,
      selectedProductId: "",
      labelCheckList: [],
      order_col: undefined,
      order_asc: undefined,
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.getselfProductSearchListData();
    });
  },
  mounted() {
    this.getsupplyproductCateListData();
    this.getselfProductSearchListData();
    this.getPageList();
    this.getCouponList();
    this.getLabelList();
  },
  methods: {
    selectShopToStore(id) {
      this.$router.push({
        path: "./addshopTostore",
        query: { type: 2, product_no: id }
      });
    },
    gotoSaleDaily(id) {
      this.$router.push({
        path: "./privateorderlist",
        query: { product_id: id }
      });
    },
    searchSupplyChain() {
      this.page = 1;
      this.getselfProductSearchListData();
    },
            tblSort(d) {
                this.order_col = d.prop;
                this.order_asc = d.order;

                this.searchSupplyChain();
            },
    
    exportWoodsStore() {
      this.is_export = 1;
      this.getselfProductSearchListData();
    },

    deleteWoods(id) {
      this.$confirm("确定删除该商品？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          this.getselfProductRemoveData(id);
        })
        .catch(() => {
          console.log("cancel");
        });
    },
    pageChange(page) {
      console.log(page);
      this.page = page;
      //申请更多数据
      this.getselfProductSearchListData();
    },
    lookMoreShop(product_no) {
      this.getsupplyProductImgListData(product_no);
      this.isShowShopImg = true;
    },
    watchSkuDetail(id) {
      this.isShowSKUInformtion = true;
      this.skuId = id;
    },
    certainshowSKUInfordetail() {
      this.isShowSKUInformtion = false;
    },

    updateStoreShop(product_no) {
      this.getselfProductOnsaleUpdateData(5, product_no);
    },
    updateDownStoreShop(product_no) {
      this.getselfProductOnsaleUpdateData(15, product_no);
    },
    recommendShopStore(id, on_sale) {
      if (on_sale === 15) {
        this.$message.error("本商品已经下架,不能推荐");
        return;
      } else {
        this.getsupplyRecommendProductData(id);
      }
    },
    //获取分类列表
    async getsupplyproductCateListData() {
      let res = await simpleGoodsTypeList();
      if (res.code === 10000) {
        this.categoryList = res.data;
      } else {
        this.$message.error(res.message);
      }
    },
    // 获取专场列表
    async getPageList() {
      const res = await getPageList();
      if (res.code === 10000) {
        console.log(res.data);
        this.pageList = res.data;
      }
    },
    // 获取优惠券列表
    async getCouponList() {
      var url = "page=1";
      const res = await easyCouponList(url);
      if (res.code === 10000) {
        console.log(res.data);
        this.couponList = res.data;
      }
    },
    // 获取标签列表
    async getLabelList() {
      const res = await getLabelList();
      if (res.code === 10000) {
        this.labelList = res.data;
      }
    },
    async getselfProductSearchListData() {
      if (this.on_sale == 0) {
        this.on_sale = "";
      }
      var str =
        "product_no=" +
        this.product_no +
        "&title=" +
        this.title +
        "&on_sale=" +
        this.on_sale +
        "&is_export=" +
        this.is_export +
        "&cate_id=" +
        this.cate_id +
        "&page=" +
        this.page +
        "&size=" +
        this.size +
        "&product_page=" +
        this.page_id +
        "&product_label=" +
        this.label_id;
        if(this.order_col) {
          str += "&order_col=" + this.order_col;

          if(this.order_asc) {
            str += "&order_asc=" + this.order_asc;
          }
        }
        if(this.product_type) {
            str += "&product_type=" + this.product_type;

        }
      let res = await selfProductSearchList(str);
      if (res.code === 10000) {
        if (this.is_export === 1) {
          this.is_export = 0;
          window.open(
            `${API_BASE_URL}/admin/download/zip/${res.data.download_token}`
          );
          return;
        } else {
          this.tableData = res.data.data;
          this.total = res.data.total;
        }
      } else {
        this.is_export = 0;
        this.$message.error(res.message);
      }
    },
    //查看sku图片
    async getsupplyProductImgListData(product_no) {
      let res = await supplyProductImgList(product_no);
      if (res.code === 10000) {
        this.img_arr = res.data;
      } else {
        this.$message.error(res.message);
      }
    },

    //更新上下架状态
    async getselfProductOnsaleUpdateData(onsale, product_no) {
      var form = { on_sale: onsale };
      let res = await selfProductOnsaleUpdate(product_no, form);
      if (res.code === 10000) {
        this.$message.success(res.message);
        this.getselfProductSearchListData();
      } else {
        this.$message.error(res.message);
      }
    },
    //移除数据
    async getselfProductRemoveData(product_no) {
      let res = await selfProductRemove(product_no);
      if (res.code === 10000) {
        this.$message.success(res.message);
        this.getselfProductSearchListData();
      } else {
        this.$message.error(res.message);
      }
    },

    //点击推荐或者不推荐
    async getsupplyRecommendProductData(product_no) {
      let res = await supplyRecommendProduct(product_no);
      if (res.code === 10000) {
        this.$message.success(res.message);
        this.getselfProductSearchListData();
      } else {
        this.$message.error(res.message);
      }
    },
    tc() {
      return "text-align:center; color:#333333; font-size:12px;";
    },
    tccolor() {
      return "text-align:center;background-color:#f5f5f5; font-size:14px;";
    },
    openPageDialog() {
      if (this.selectedItems.length === 0) {
        this.$message.error("请至少选中一项!");
        return false;
      }
      this.dialogVisible = true;
    },
    // 选中商品加入优惠券
    openCouponDialog() {
      if (this.selectedItems.length === 0) {
        this.$message.error("请至少选中一项!");
        return false;
      }
      this.dialogCouponVisible = true;
    },
    // 确定添加商品关联到优惠券
    addToCouponShop() {
      const params = {
        coupon_ids: this.checkList.join(","),
        add_relates: this.selectedItems.join(",")
      };
      console.log(params);
      isShopCouponChange(params).then(res => {
        if (res.code === 10000) {
          this.$message.success("添加商品成功");
          this.dialogCouponVisible = false;
          this.checkList = [];
          this.getselfProductSearchListData();
        } else {
          this.$message.error(res.message);
        }
      });
    },

    addToSpecialSession() {
      const params = {
        page_id: this.checkList.join(","),
        product_id: this.selectedItems.join(",")
      };
      console.log(params);
      addToProductPage(params).then(res => {
        if (res.code === 10000) {
          this.$message.success("添加专场成功");
          this.dialogVisible = false;
          this.checkList = [];
          this.getselfProductSearchListData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    cancel() {
      this.dialogVisible = false;
      this.dialogCouponVisible = false;
      this.checkList = [];
    },
    handleSelectionChange(value) {
      console.log(value);
      this.selectedItems = [];
      value.map(item => {
        this.selectedItems.push(item.id);
      });
    },
    orderSortChange(productNo, orderSort) {
      const params = {
        order_sort: orderSort
      };
      setOrderSort(productNo, params).then(res => {
        console.log(res);
      });
    },
    showLabelDialog(id) {
      this.labelDialogVisible = true;
      this.selectedProductId = id;
    },
    updateProductLabel() {
      if (this.labelCheckList.length === 0) {
        this.$message.error("请至少选中一个标签");
        return;
      }
      if (this.labelCheckList.length > 2) {
        this.$message.error("最多选择两个标签");
      }
      const params = {
        label_id: this.labelCheckList.join(",")
      };
      updateLabel(this.selectedProductId, params).then(res => {
        if (res.code === 10000) {
          this.$message.success("设置成功！");
          this.labelDialogVisible = false;
          this.labelCheckList = [];
          this.getselfProductSearchListData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    labelCancel() {
      this.labelDialogVisible = false;
      this.labelCheckList = [];
    }
  }
};
</script>
<style lang="scss" scoped>
.label {
  border-radius: 5px;
  padding: 2px;
  margin-left: 10px;
}
.shop {
  padding: 20px;
  .top {
    margin-bottom: 20px;
    .search {
      float: right;
      margin-left: 12px;
    }
    .input {
      width: 150px;
    }
  }
  .img {
    float: left;
  }
  .more {
    width: 60px;
    float: right;
    line-height: 100px;
    color: #f4222d;
    cursor: pointer;
  }
  .setting-label {
    line-height: 100px;
    color: red;
    cursor: pointer;
  }
  .pagination {
    float: right;
    margin-top: 12px;
  }

  .syncdata {
    width: 100%;
    height: 300px;
    .sync-load {
      width: 100%;
      height: 140px;
      margin-top: 20px;
    }
    .sync-ing {
      text-align: center;
      color: #999999;
      font-size: 12px;
    }
    .sync_num {
      text-align: center;
      font-size: 12px;
      margin-top: 15px;
    }
  }

  .sku_pic {
    padding: 12px 20px;
    .sku_pic_margin {
      margin: 12px 12px;
    }
    .main_sku {
      position: relative;
      float: left;
    }
    .main_img {
      position: absolute;
      bottom: 0;
      left: 12px;
      background-color: #f5f5f5;
      color: #f4222d;
      text-align: center;
      font-size: 14px;
      line-height: 30px;
      height: 30px;
      width: 160px;
    }
    .other_img {
      color: rgb(71, 255, 47);
    }
  }
  .rec_success {
    font-size: 40px;
    color: green;
  }
  .rec_failure {
    color: #f4222d;
    font-size: 40px;
  }
}
</style>
